#!/bin/bash

set -eu -o pipefail

deps_exec=(git xdelta3 aria2c unzip)

scripts_path=`cd "\`dirname \"$0\"\`"; echo "$PWD"`

check_deps() {
  code=0
  for dep in ${deps_exec[@]}; do
    if ! command -v $dep >/dev/null; then
      code=1
      echo "$dep"
    fi
  done
  exit $code
}

install_deps() {
  declare -A managers=(
      [apt]="install -y git xdelta3 aria2 unzip"
      [yum]="install -y git xdelta aria2 unzip"
      [dnf]="install -y git xdelta3 aria2 unzip"
      [pacman]="-S --noconfirm xdelta3 aria2 unzip"
  )
  pkg=
  for p in ${!managers[@]}; do
    if command -v $p >/dev/null 2>&1; then
      pkg="$p ${managers[$p]}"
      break
    fi
  done

  if [ -z "$pkg" ]
  then
    echo "Cannot detect package manager" >&2
    exit 1
  fi

  tmp=$(mktemp)
  trap "rm $tmp" EXIT
  if ! "$scripts_path/sudo-wrapper" $pkg 2>$tmp; then
    cat $tmp
    exit 1
  fi
  echo "Dependencies installed successfully"
}



case "${1:-?}" in
  check)
    check_deps
    ;;

  install)
    install_deps
    ;;

  *)
    echo "$0 [check|install]" >&1
    exit 1
    ;;
esac
